import threading
import time


class RepeatedTimer:
    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = threading.Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False


def task():
    print("Task executed at: ", time.strftime(
        "%Y-%m-%d %H:%M:%S", time.localtime()))


if __name__ == "__main__":
    rt = RepeatedTimer(0.3, task)

    # 让主程序运行一段时间
    time.sleep(5)

    # 暂停定时任务
    rt.stop()
    print("Task stopped.")

    # 再次启动定时任务
    rt.start()
    time.sleep(5)

    # 最后停止定时任务
    rt.stop()
    print("Task stopped again.")
